package com.dcy.znoa.controller.publiz;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.dcy.znoa.common.annotation.AuthenticationAPI;
import com.dcy.znoa.common.controller.BaseController;
import com.dcy.znoa.common.exception.BusinessException;
import com.dcy.znoa.common.util.Dysms;
import com.dcy.znoa.common.util.RedisClient;
import com.dcy.znoa.common.util.StringRandom;
import com.dcy.znoa.common.util.excel.ExcelOutput;
import com.dcy.znoa.common.util.pojo.JsonCommon;
import com.dcy.znoa.common.util.pojo.JsonForList;
import com.dcy.znoa.controller.publiz.model.oper.*;
import com.dcy.znoa.dao.publiz.DepartmentDao;
import com.dcy.znoa.dao.user.OperDao;
import com.dcy.znoa.domain.Oper;
import com.dcy.znoa.domain.publiz.Department;
import com.dcy.znoa.service.software.OperService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.dcy.znoa.common.util.Dysms.get6RandNum;
import static com.dcy.znoa.common.util.pojo.JsonCommon.SUCCESS_CODE;
import static com.dcy.znoa.common.util.pojo.JsonCommon.SUCCESS_MSG;
import static com.dcy.znoa.domain.Oper.DEFAULT_PASSWORD;
import static com.dcy.znoa.domain.publiz.Department.TO_AUDIT;

/**
 * Created by pengyu on 2017/10/23.
 * 用户controller：包括管理员与企业用户
 */
@Slf4j
@Controller
@RequestMapping("oper")
public class OperController extends BaseController {

    @Autowired
    OperService operService;
    @Autowired
    DepartmentDao departmentDao;
    @Autowired
    OperDao operDao;

    //APP：获取手机验证码，同时传给APP，APP即可验证短信码
    @ResponseBody
    @RequestMapping("/getSmsCode")
    public JsonCommon getSmsCode(String phoneNo,Integer smsType) throws BusinessException, ClientException {
        if(smsType==null || smsType>3 || smsType <1){
            return new JsonCommon("404","smsType不能为空，只能为1-3中的一个");
        }
        //1：注册2：忘记密码 如果为2，那么先判断手机号码是否存在库中 3：修改手机号
        Oper operQuery = new Oper();
        operQuery.setPhoneNo(phoneNo);
        operQuery.setValidFlag(1);
        Oper oper = operDao.selectOne(operQuery);
        switch(smsType){
            case 1:
            case 3:
                if(oper!=null){
                    return new JsonCommon("404","此手机号码已经注册");
                }
                break;
            case 2 :
                if(oper == null){
                    return new JsonCommon("404","此手机号码不存在平台中或已被禁用");
                }
                break;
             default:
                 return new JsonCommon("404","smsType只能为1或2");
        }
        //60秒内不允许再次获取验证码
        String smsCode = RedisClient.get(RedisClient.DYSMS_PREFIX + phoneNo);
        if(StringUtils.isNotBlank(smsCode)){
            return new JsonCommon("404","60秒内不允许重复发送验证码");
        }
        String rndPwd = get6RandNum();
        log.info("validSms = "+rndPwd);
        SendSmsResponse ssr = Dysms.sendSms(Dysms.RND_CODE,phoneNo,rndPwd);
        if(ssr!=null){
            String responseCode = ssr.getCode();
            if("OK".equals(responseCode)){
                return new JsonCommon(rndPwd,SUCCESS_CODE,SUCCESS_MSG);
            }
            log.error(phoneNo+" smsError: " + ssr.getMessage());
            return new JsonCommon("404",ssr.getMessage());
        }
        return new JsonCommon("404","短信服务不可用");
    }
    //暂时不需要此方法
    @ResponseBody
    @RequestMapping("/validateSms")
    public JsonCommon validateSms(String phoneNo,String smsCode) throws BusinessException{
        return null;
    }
    //app
    @ResponseBody
    @RequestMapping("/register")
    public JsonCommon register(RegisterOperModel model,BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if (bindingResult.hasErrors()){
            return  new JsonCommon("404",bindingResult.getFieldError().getDefaultMessage());
        }
        model.setCompId(model.getCompanyId());
        Oper cp = new Oper();
        BeanUtils.copyProperties(cp, model);
        if(cp.getPassword() == null){
            cp.setPassword(DEFAULT_PASSWORD);
        }
//        //查询该公司根节点部门ID
//        Department department = new Department();
//        department.setCompId(model.getCompanyId());
//        department.setDepLevel(1);
//        Department depResult =  departmentDao.selectOne(department);
//        if(depResult!=null){
//            cp.setDepId(depResult.getDepId());
//        }
        //如果公司有TO_AUDIT的部门，就放到TO_AUDIT的部门，没有的话，就放到根节点部门
        Department depQuery = new Department();
        depQuery.setDepName(TO_AUDIT);
        depQuery.setCompId(model.getCompId());
        Department toAuditDep = departmentDao.selectOne(depQuery);
        if(toAuditDep!=null){
            cp.setDepId(toAuditDep.getDepId());
        }else{
            return  new JsonCommon("404","此公司目录下没有 "+TO_AUDIT+" 这个部门，请联系管理员");
        }
//        cp.setEmployeeNo(StringRandom.getStringRandom(8));
        operService.save(cp);
        return new JsonCommon(SUCCESS_CODE);
    }
    //WEB
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/query")
    public JsonForList query(SelectOperModel model,BindingResult result) throws BusinessException, InvocationTargetException, IllegalAccessException {
        return operService.queryList(model);
    }

    //WEB
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/add")
    public JsonCommon add(@Valid AddOperModel model, BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if (bindingResult.hasErrors()){
            return  new JsonCommon("404",bindingResult.getFieldError().getDefaultMessage());
        }
        Oper cp = new Oper();
//        model.setCreateOperId(getCurrentUser().getOperId());
        model.setCreateOperName(getCurrentUser().getOperName());
        BeanUtils.copyProperties(cp, model);
        if(StringUtils.isBlank(cp.getPassword())){
            cp.setPassword(DEFAULT_PASSWORD);
        }
        operService.save(cp);
        return new JsonCommon(SUCCESS_CODE);
    }
    //通用
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/updateById")
    public JsonCommon update(@Valid UpdateOperModel model,BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if (bindingResult.hasErrors()){
            return  new JsonCommon("404",bindingResult.getFieldError().getDefaultMessage());
        }
        Oper cp = new Oper();
//        model.setUpdateOperId(getCurrentUser().getOperId());
        BeanUtils.copyProperties(cp, model);
//        Integer updateResult = operService.update(cp);
        Oper operResult = operService.update(cp);
//        if(updateResult !=null && updateResult>0){
//            return new JsonCommon(operResult);
//        }
        if(operResult!=null){
            return new JsonCommon(operResult);
        }
        return new JsonCommon("404","更新失败，系统错误");

    }
    //通用
    @ResponseBody
    @RequestMapping("/updatePwd")
    public JsonCommon updatePwd(@Valid UpdatePwdModel model,BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if (bindingResult.hasErrors()){
            return  new JsonCommon("404",bindingResult.getFieldError().getDefaultMessage());
        }
        Oper operResult = operService.updatePwd(model);
        if(operResult!=null){
            return new JsonCommon(operResult);
        }
        return new JsonCommon("404","更新失败，系统错误");

    }


    //通用
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/logicDelById")
    public JsonCommon logicDel(@Valid LogicDelOperModel model,BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if (bindingResult.hasErrors()){
            return  new JsonCommon("404",bindingResult.getFieldError().getDefaultMessage());
        }
        Oper cp = new Oper();
        model.setUpdateOperId(getCurrentUser().getOperId());
        BeanUtils.copyProperties(cp, model);
//        Integer updateResult = operService.update(cp);
//        if(updateResult !=null && updateResult>0){
//            return new JsonCommon(SUCCESS_CODE);
//        }
        Oper operResult = operService.update(cp);
//        if(updateResult !=null && updateResult>0){
//            return new JsonCommon(operResult);
//        }
        if(operResult!=null){
            return new JsonCommon(operResult);
        }
        return new JsonCommon("404","逻辑删除失败，系统错误");
    }


    //WEB 批量启用 或 批量禁用
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/batchValid")
    public JsonCommon batchValid(@Valid BatchValidOperModel model,BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if (bindingResult.hasErrors()){
            return  new JsonCommon("404",bindingResult.getFieldError().getDefaultMessage());
        }
        Oper cp = new Oper();
        model.setUpdateOperId(getCurrentUser().getOperId());
        BeanUtils.copyProperties(cp, model);
        Integer updateResult = operService.batchValid(model);
        if(updateResult !=null && updateResult>0){
            return new JsonCommon(SUCCESS_CODE);
        }
        return new JsonCommon("404","逻辑删除失败，系统错误");
    }

    //WEB 导出 暂时先做单表导出，需求不明确，字段也不明确
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/export")
    public JsonCommon export(@Valid SelectOperModel model,BindingResult bindingResult,HttpServletRequest request, HttpServletResponse response) throws BusinessException, InvocationTargetException, IllegalAccessException, IOException {
        if (bindingResult.hasErrors()) {
            return new JsonCommon("404", bindingResult.getFieldError().getDefaultMessage());
        }
        List<Map<String, Object>> recordList = new ArrayList<>();
        JsonForList  jsonForList = operService.queryList(model);
        List<Oper> list = jsonForList.getData();
        for(Oper oper :list ){
            recordList.add(Oper.toMap(oper));
        }
        String keys[] = {"operId", "operType", "phoneNo", "operName", "compName", "depName",  "dutyName", "dutyNo", "sex", "idCard", "qrCode"};//map中的key
        String columnNames[] = {"用户ID", "用户类型", "电话号码", "姓名", "公司名称", "部门名称", "职务", "工号", "性别", "身份证号", "二维码号"};//列名
        ExcelOutput.ExcelOutput(request, response, recordList, keys, columnNames, "用户列表");
        return new JsonCommon(SUCCESS_CODE);
    }
    //适用于APP
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/modifyPwd")
    public JsonCommon modifyPwd(String pwd) throws BusinessException, InvocationTargetException, IllegalAccessException {
        Integer updateResult = operService.modifyPwd(getCurrentUser().getOperId(),pwd);
        if(updateResult !=null && updateResult>0){
            return new JsonCommon(SUCCESS_CODE);
        }
        return new JsonCommon("804","修改密码失败，系统错误");
    }

    //适用于WEB端
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/top")
    public JsonCommon top(Long operId) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if(operId==null){
            return new JsonCommon("404","接口需要用户ID");
        }
        Integer topResult = operService.top(operId);
        if(topResult !=null && topResult>0){
            return new JsonCommon(SUCCESS_CODE);
        }
        return new JsonCommon("804","用户置顶失败，系统错误");
    }

    //适用于WEB端
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/audit")
    public JsonCommon audit(@Valid AuditOperModel model,BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if (bindingResult.hasErrors()){
            return  new JsonCommon("404",bindingResult.getFieldError().getDefaultMessage());
        }
        model.setAuditOperName(getCurrentUser().getOperName());
        Integer topResult = operService.audit(model);
        if(topResult !=null && topResult>0){
            return new JsonCommon(SUCCESS_CODE);
        }
        return new JsonCommon("804","用户审核失败，系统错误");
    }



}
